package com.yq.tanhua.ui.chat.chatlist

import android.widget.Toast
import com.blankj.utilcode.util.ToastUtils
import com.fmt.mvi.learn.gobal.log
import com.google.gson.Gson
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMConversation
import com.hyphenate.chat.EMCursorResult
import com.hyphenate.chat.EMMessage
import com.yq.tanhua.im.ImUtils
import com.yq.tanhua.net.BaseViewModel
import com.yq.tanhua.net.TanHuaApiService
import com.yq.tanhua.ui.detail.CommonRequestState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.runBlocking
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import kotlin.jvm.internal.Intrinsics.Kotlin

/**
 * @author: user
 * @date: 2023/5/11
 */
class ChatListViewModel : BaseViewModel() {


    private val _chatListUIState =
        MutableStateFlow(ChatListUiData(requestState = CommonRequestState.Loading))
    val chatListUiState = _chatListUIState.asStateFlow()

    fun loadServerMessages(conversationId: String, conversationType: Int) {

        val conversation = EMClient.getInstance().chatManager()
            .getConversation(conversationId)

        try {
            val msgs = conversation.loadMoreMsgFromDB("", 10)
            _chatListUIState.update {
                it.copy(
                    requestState = CommonRequestState.LoadSuccess,
                    chatList = msgs
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
            _chatListUIState.update {
                it.copy(requestState = CommonRequestState.LoadFail("请求失败"))
            }
        }


    }

    fun addContract(userId: String) {
        launch({
            val map: HashMap<String, Any> = HashMap()
            map.put("userId", userId)
            val jsonParam = Gson().toJson(map)
            val body =
                jsonParam.toRequestBody("application/json;charset=utf-8".toMediaType())
            TanHuaApiService.addContacts(body)
            ToastUtils.showShort("添加成功")
        }, {
            ToastUtils.showShort("添加失败："+it.message)

        })
    }
}

data class ChatListUiData(
    val requestState: CommonRequestState,
    val chatList: List<EMMessage>? = null
)